class IconSvg extends HTMLElement {
  static get observedAttributes() {
    return ['name', 'size', 'color']
  }

  constructor() {
    super()
    const shadowRoot = this.attachShadow({ mode: 'open' })
    shadowRoot.innerHTML = `
      <style>
      :host{
        font-size:inherit;
        display:inline-block;
        transition:.3s;
      }
      .icon {
        vertical-align: -0.15em;
        width: 1em;
        height: 1em;
        margin: auto;
        fill: currentColor;
        overflow: hidden;
      }
      :host([spin]){
        animation: rotate 1.4s linear infinite;
      }
      @keyframes rotate{
        to{
            transform: rotate(360deg); 
        }
      }
      </style>
      <svg class="icon" id="icon" aria-hidden="true">
        <use id="use"></use>
      </svg>
    `
  }

  get name() {
    return this.getAttribute('name')
  }

  set name(value) {
    this.setAttribute('name', value)
  }

  get size () {
    return this.getAttribute('size') || ''
  }

  set size (value) {
    this.setAttribute('size', value)
  }

  get color () {
    return this.getAttribute('color') || ''
  }

  set color (value) {
    this.setAttribute('color', value)
  }

  connectedCallback() {
    this.icon = this.shadowRoot.getElementById('icon')
    this.use = this.icon.querySelector('use')
    this.name && (this.name = this.name)
    this.size && (this.size = this.size)
    this.color && (this.color = this.color)
  }

  attributeChangedCallback(name, oldValue, newValue) {
    if (name == 'name' && this.use) {
      this.use.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', `../iconfont/icon.svg#icon-${newValue}`)
    }
    if (name === 'size' && this.icon) {
      this.icon.style.fontSize = newValue + 'px'
    }
    if (name === 'color' && this.icon) {
      this.icon.style.color = newValue
    }
  }
}

customElements.define('icon-svg', IconSvg)
